<template>
  <div class="CommonPictureUpload">
    <div class="img-wrap item" v-for="(item, index) in currentValue" :key="item">
      <img :src="generateImgUrl(item)" @click="handleViewPhoto(item)" mode="scaleToFill" />
      <van-icon name="clear" color="#D1272F" @click="handleClearPhoto(index)" v-if="!isView" />
    </div>
    <div class="btn-wrap item" @click="handleChoosePhoto" v-show="!isView" v-if="(isMultiple && currentValue.length < length) || (!isMultiple && currentValue.length < 1)">
      <i class="iconfont iconpaishe" style="font-size: 54px;"></i>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import wxp from '@/utils/wxp'
import { generateImgUrl } from '@/utils'
import isEqual from 'lodash.isequal'
import cloneDeep from 'lodash.clonedeep'

export default {
  props: {
    value: {
      type: [String, Array],
      required: true,
    },
    isOnlyCamera: {
      type: Boolean,
    },
    data: {
      type: Object,
      default () {
        return {}
      },
    },
    api: {
      type: Function,
      default () {
        return api.uploadFile
      },
    },
    length: {
      type: Number,
      default: 9999,
    },
    beforeUpload: {
      type: Function,
      default () {
        return (filePath) => filePath
      },
    },
    isView: {
      type: Boolean,
    },
  },
  data () {
    return {
      generateImgUrl,
      currentValue: [],
    }
  },
  computed: {
    isMultiple () {
      return Array.isArray(this.value)
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler (newVal, oldVal) {
        if (!this.isMultiple) {
          // 单张图
          if (this.value === this.currentValue) {
            return
          }
          if (this.value) {
            this.currentValue = [this.value]
          } else {
            this.currentValue = []
          }
        } else {
          // 多张图
          if (!isEqual(this.value, this.currentValue)) {
            this.currentValue = cloneDeep(this.value)
          }
        }
      },
    },
  },
  methods: {
    async handleChoosePhoto () {
      const { tempFilePaths } = await wxp.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', this.isOnlyCamera ? undefined : 'album'],
      })
      const filePath = await this.beforeUpload(tempFilePaths[0])
      const { result } = await this.api(Object.assign({}, { filePath, name: 'file' }, this.data))
      if (!this.isMultiple) {
        this.currentValue = [result.path]
        this.$emit('input', result.path)
      } else {
        this.currentValue.push(result.path)
        this.$emit('input', cloneDeep(this.currentValue))
      }
    },
    handleViewPhoto (item) {
      wx.previewImage({
        urls: [generateImgUrl(item)],
      })
    },
    handleClearPhoto (index) {
      if (!this.isMultiple) {
        this.currentValue = []
        this.$emit('input', '')
      } else {
        this.currentValue.splice(index, 1)
        this.$emit('input', cloneDeep(this.currentValue))
      }
    },
  },
}
</script>

<style lang="scss" scoped> @import "~css/var.scss";

.CommonPictureUpload {
	display: flex;
	flex-wrap: wrap;
	margin: 10px;

	.item:not(:last-child) {
		margin-right: 15px;
		margin-bottom: 5px;
	}

	.btn-wrap {
		width: 80px;
		height: 80px;
		border: 1px solid rgba(230, 230, 230, 1);
		border-radius: 5px;
		line-height: 80px;
		text-align: center;
		font-size: 30px;
		color: #e6e6e6;
	}

	.img-wrap {
		display: inline-block;
		position: relative;

		img {
			overflow: hidden;
			width: 80px;
			height: 80px;
			border-radius: 8px;
		}

		.van-icon {
			/* in global.scss */
		}
	}
}
</style>
